package service.dataBase;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import service.exceptions.BadQueryInputException;

public class Query {

	private DataBase db;


	public Query(DataBase db) {
		this.db = db;
	}

	public ArrayList<Object[]> selectFromTable(String table, String fields,String condition) throws BadQueryInputException{
		ResultSet queryResult;
		ArrayList<Object[]> output = new ArrayList<Object[]>();
		
		if (condition == null) {
			try {
				queryResult = db.getStatment().executeQuery("SELECT " + fields + " FROM " + table);
			} catch (SQLException e) {
				throw new BadQueryInputException("error");
			}
		}else{
			try {
				queryResult = db.getStatment().executeQuery("SELECT " + fields + " FROM " + table+ " WHERE "+condition);
			} catch (SQLException e) {
				throw new BadQueryInputException("error");	
			};
		}
		
		try {
			while (queryResult.next()) {
				Object[] outputLine=new Object[queryResult.getMetaData().getColumnCount()];
				for(int i=1;i<=queryResult.getMetaData().getColumnCount();i++){
					outputLine[i-1]=queryResult.getObject(i);
				}
				output.add(outputLine);
			}
		} catch (SQLException e) {
			throw new BadQueryInputException("error");
		}
		return output;
	}
	
	public void PrintQuery (ArrayList<Object[]> arrayList){
		for (int i=0;i<arrayList.size();i++){
			for (int j=0;j<arrayList.get(i).length;j++){
			if(arrayList.get(i)[j]!=null){
				System.out.print(arrayList.get(i)[j].toString()+"|");	
			}else{
				System.out.print("---|");
			}
			}
			System.out.print("\n");
		}
	}
}
